package com.yeswater.rabbitmq;

import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.DeliverCallback;
import com.yeswater.rabbitmq.utils.RabbitmqUtil;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/**
 * 死信队列实战 消费者
 * Author : yeswater
 */

public class Customer01 {

    // 普通交换机
    public static final String NORMAL_EXCHANGE = "normal_exchange";
    // 死信交换机
    public static final String DEAD_EXCHANGE = "dead_exchange";
    // 普通队列
    public static final String NORMAL_QUEUE = "normal_queue";
    // 死信队列
    public static final String DEAD_QUEUE = "dead_queue";

    public static void main(String[] args) throws Exception {
        Channel channel = RabbitmqUtil.getChannel();

        // 声明死信和普通交换机
        channel.exchangeDeclare(NORMAL_EXCHANGE, BuiltinExchangeType.DIRECT);
        channel.exchangeDeclare(DEAD_EXCHANGE, BuiltinExchangeType.DIRECT);

        Map<String, Object> arguments = new HashMap<>();
        // arguments.put("x-message-ttl", 10 * 1000); // 死信方式一: 过期时间
        arguments.put("x-dead-letter-exchange", DEAD_EXCHANGE);
        arguments.put("x-dead-letter-routing-key", "dead");
        // arguments.put("x-max-length", 6); // 死信方式二: 队列长度


        // 声明普通队列
        channel.queueDeclare(NORMAL_QUEUE, false, false, false, arguments);
        // 声明死信队列
        channel.queueDeclare(DEAD_QUEUE, false, false, false, null);

        //绑定交换机和队列
        channel.queueBind(NORMAL_QUEUE, NORMAL_EXCHANGE, "normal");
        channel.queueBind(DEAD_QUEUE, DEAD_EXCHANGE, "dead");

        System.out.println("等到接收消息...");

        DeliverCallback deliverCallback = (consumerTag, message) -> {
            String msg = new String(message.getBody(), StandardCharsets.UTF_8);
            if ("info1".equals(msg)) {
                // 死信方式三: 拒绝
                channel.basicReject(message.getEnvelope().getDeliveryTag(),false);
                System.out.println("consumer01 拒绝消息: " + msg);
                // channel.basicNack();
            }else{
                channel.basicAck(message.getEnvelope().getDeliveryTag(),false);
                System.out.println("consumer01 接收消息: " + msg);
            }
        };

        channel.basicConsume(NORMAL_QUEUE, false, deliverCallback, (consumerTag) -> {
        });
    }


}
